<?php

namespace app\admin\middleware;

use app\admin\logic\system\LoginLogic;
use app\admin\model\model\system\SystemAccount;
use app\admin\model\model\system\SystemAccountAuth;
use app\admin\model\model\system\SystemMenu;
use app\Request;
use think\Exception;

/**
 * 验证登录及权限
 */
class Auth
{
    // 控制器白名单
    private $allowController = [
        'system.upload'
    ];

    private $allowMethod = [
        'system.menu_getdata',
        'index_index',
    ];

	public function handle(Request $request, $next) {
		// 验证登录
		if(!LoginLogic::check()) {
			return redirect(url('login/index'));
		}
        return $next($request);

        if($this->checkAllowController($request)) {
            return $next($request);
        }

        if($this->checkAllowMethod($request)) {
            return $next($request);
        }

        if(!$this->checkAuth($request)) {
            throw new Exception('无权限');
        }

		return $next($request);
	}

    protected function checkAllowController(Request $request) {
        return in_array(strtolower($request->controller()), $this->allowController);
    }

    protected function checkAllowMethod(Request $request) {
        $method = strtolower($request->controller() .'_'. $request->action());
        return in_array($method, $this->allowMethod);
    }

    protected function checkAuth(Request $request) {
        // 验证菜单
        // 获取当前控制器
        $controller = $request->controller(true);

        $url = '/' . $controller . '/index';

        // 查表获取控制器是否存在
        $id = SystemMenu::getIdByUrl($url);
        if(!$id) {
            throw new Exception('地址错误');
        }

        // 判断是否有权限
        $accountId = LoginLogic::getId();

        // 超级管理员
        if($accountId === SystemAccount::USER_SUPER) {
            return true;
        }

        $res = SystemAccountAuth::check($accountId, $id);
        if(!$res) {
            throw new Exception('无权限');
        }

        return true;
    }
}